package com.smart.framework.util;

/**
 * <p><b>Description:</b>  TODO
 * <p><b>Company:</b>
 *
 * @author created by Jesse Xu at 15:41 on 2019/11/26
 * @version V0.1
 * @classNmae BinarySearch
 */
public class BinarySearch {

    /**
     * 如果精度太高，是进入死循环 scale 最高设置为10
     * @param s
     * @param scale
     * @return
     */
    public static double sqrt(double s,int scale){
        if(scale>10){
            scale =10;
        }
         double root =0;
         //查找整数
        double low = 0;
        double high = s;
        double mid =0;
        double d =1;
        double res =0;
        for (int i=0;i<=scale;i++){
            while (low<=high){
                mid = low + (high - low)/2;
                mid =Double.valueOf( String.format("%."+i+"f", mid));
                if(mid*mid==s){
                    return mid;
                }
                if(mid*mid<s){
                    low = mid+d;
                }
                if(mid*mid>s){
                    high = mid-d;
                }
            }
            low =mid-d;
            high =mid+d;
            d*=0.1;
        };
         return mid;
    }


    public static void main(String[] args) {
        System.out.println(Math.sqrt(50));
        System.out.println(sqrt(50,16));
    }
}
